<template>
  <span>
    <slot :loading="loading" :click="onClick" :upload="onUpload"></slot>
    <input ref="input" type="file" style="display:none" @change="onUpload" />
  </span>
</template>
<script setup>
  import { ref } from 'vue'
  import { upload } from '@/api/manage'

  const props = defineProps(['modelValue'])
  const emit = defineEmits(['modelValue'])

  // 控件
  const input = ref(null)
  const loading = ref(false)

  // 选择文件
  const onClick = () => {
    input.value.click()
  }

  // 上传
  const onUpload = (e) => {
    const file = e.target.files;

    // 取单文件
    if(file.length > 0) {
      loading.value = true
      upload('image', file[0]).then(res => {
        emit('update:modelValue', res.url)
      }).finally(() => {
        loading.value = false
      })
    }
  }
</script>